import { menus } from '@/api/account'
import { BUTTON, ROLE_ID, USER_INFO } from '@/config/constants'
import { defineStore } from 'pinia'
import { reactive } from 'vue'
import { Message } from '@arco-design/web-vue'
import { root, constantRouterComponents } from '@/router/constRoutes'
import { resetRouter } from '@/router/index'

const modules = import.meta.glob('../views/**/*.vue')

export const useRoutesStore = defineStore('routes', () => {
  const asyncRoute = reactive({
    routes: [],
    menus: [],
    buttons: []
  })

  const loadMenus = () => {
    return new Promise((resolve, reject) => {
      let userInfo = JSON.parse(localStorage.getItem(USER_INFO));
      menus({ roleId: userInfo.roleid }).then((res) => {
        if (res.code === 200) {
          asyncRoute.buttons = res.data.buttons
          localStorage.setItem(BUTTON, res.data.buttons)
          asyncRoute.menus = res.data.menus
          let routes = root.concat([...transfer(res.data.routes)])
          asyncRoute.routes = routes
        } else {
          Message.error(res.message)
        }
        resolve()
      }).catch((e) => {
        reject(e)
      })
    })
  }
  const transfer = (routes) => {
    return routes.map((item) => {
      item.component = item.component
        ? constantRouterComponents[item.component] || modules[`../views${item.component}.vue`]
        : null
      if (item.children) {
        transfer(item.children)
      }
      return item
    })
  }

  const resetRouterStore = () => {
    asyncRoute.routes = []
    asyncRoute.menus = []
    asyncRoute.buttons = []
    resetRouter()
  }
  return {
    asyncRoute,
    loadMenus,
    resetRouterStore
  }
})
